package com.itheima.aspect;

import com.itheima.domain.SysLog;
import com.itheima.service.EquipmentService;
import com.itheima.service.SysLogService;
import com.itheima.util.MyLog;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Date;

@Component
@Aspect
public class LogAspect {
    @Autowired
    private SysLogService sysLogService;

    //定义切入点
    @Pointcut("execution(* com.itheima.service.impl.EquipmentServiceImpl.*(..))")
    public void pt() {}

    //使用环绕通知增强方法
    @Around("pt()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        //执行原有业务
        Object obj = pjp.proceed(pjp.getArgs());
        //获取目标类的Class对象
        Class<?> clazz = pjp.getTarget().getClass();
        //获取要增强的方法
        Signature signature = pjp.getSignature();
        if(signature instanceof MethodSignature) {
            //获取方法名和方法  参数类型的Class对象
            MethodSignature ms = (MethodSignature) signature;
            String methodName = ms.getName();
            Class[] methodType = ms.getParameterTypes();
            //使用反射获取该方法Method对象
            Method method = clazz.getDeclaredMethod(methodName, methodType);
            //判断方法上是否有MyLog注解
            if (method.isAnnotationPresent(MyLog.class)) {
                //如果有就将方法相关信息添加到日志表，获取注解value信息
                MyLog annotation = method.getAnnotation(MyLog.class);
                String operation = annotation.value();
                SysLog sysLog = new SysLog();
                sysLog.setUsername("admin");
                sysLog.setOperation(operation);
                sysLog.setMethod(methodName);
                sysLog.setParams(Arrays.toString(pjp.getArgs()));
                sysLog.setCreated(new Date());
                //使用SysLogService实现类对象调用方法添加日志
                sysLogService.insertLog(sysLog);
                System.out.println("日志添加成功！！！");
            }
        }
        return obj;
    }

}
